import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Modal} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, FORM_BIG_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl} from './intl';
import styles from './style.css';
import PartSelectPanel from './PartSelectPanel';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import DropdownMenu from 'Shared/components/DropdownMenu';
import Return from '../common/Return';
import {newOrUpdateValidator} from './validator';
import {getDetail} from './api';
import FileUpload from './FileUpload';

const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
const FormItem = Form.Item;
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showPartSelectPanel: false,
        details: [],
        showFile: false,
        errorDetails: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateValidator(data, details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onDeleteDetail = e => {
        const partId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.partId !== partId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    onClickUpload = e => {
        const {id} = e.target.dataset;
        this.setState({
            currentDetailId: id,
            showFile: true
        });
    };
    onCloseFileModal = () => {
        this.setState({
            showFile: false,
            currentDetailId: '',
        });
    };
    onChangeUpload = data => {
        const details = this.state.errorDetails.filter(item => !(item.partId === this.state.currentDetailId));
        this.setState({
            hasOperat: true,
            errorDetails: details
        });
        this.onUpdateAttachments(data, this.state.currentDetailId);
    }
    onRemove = data => {
        const {details = EMPTY_ARRAY} = this.state;
        const {attachments = EMPTY_ARRAY} = details.find(item => item.partId === this.state.currentDetailId) || EMPTY_OBJECT;
        const errorDetails = attachments.length - 1 <= 0 ? [...this.state.errorDetails, {
            partId: this.state.currentDetailId
        }] : this.state.errorDetails;
        this.setState({
            hasOperat: true,
            errorDetails
        });
        this.onRemoveAttachments(data, this.state.currentDetailId);
    }
    onUpdateAttachments = (data, currentDetailId) => {
        const details = this.state.details || EMPTY_ARRAY;
        let attachments = EMPTY_ARRAY;
        const tmp = details.map(d => {
            if(d.partId === currentDetailId) {
                attachments = d.attachments || EMPTY_ARRAY;
                attachments.push({
                    fileId: data.id,
                    fileName: data.fileName
                });
                return Object.assign({}, d, {
                    attachments: [...attachments]
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onRemoveAttachments = (data, currentDetailId) => {
        const details = this.state.details || EMPTY_ARRAY;
        let attachments = EMPTY_ARRAY;
        const tmp = details.map(d => {
            if(d.partId === currentDetailId) {
                attachments = d.attachments || EMPTY_ARRAY;
                attachments.splice({
                    fileId: data.id,
                    fileName: data.name
                }, 1);
                return Object.assign({}, d, {
                    attachments: [...attachments]
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onClickAddBtn = () => {
        this.setState({showPartSelectPanel: true});
    }
    onClosePartSelectPanel = () => {
        this.setState({showPartSelectPanel: false});
    }
    onSelectPart = records => {
        const retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.partId === r.id);
            if(index === -1)
                retailDetails.push({
                    brandId: r.brandId,
                    brandCode: r.brandCode,
                    partId: r.id,
                    partCode: r.code,
                    partName: r.name,
                    specialName: r.specialName,
                    productCategoryCode: r.productCategoryCode,
                    minPackSize: r.minPackSize,
                    partCategory: r.partCategory,
                    overseaOnly: r.overseaOnly,
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showPartSelectPanel: false
        });
    }
    onChangeDetail = (value, id, e) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.partId === id)
                return Object.assign({}, d, {
                    [e.target.name]: value
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onChangeConsume = e => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.partId === e.target.id)
                return Object.assign({}, d, {
                    [e.target.name]: e.target.checked
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onUpdateQuantity = (planQuantity, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.partId === id)
                return Object.assign({}, d, {
                    planQuantity,
                    isColor: false
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const {areas} = this.props;
        const validateCountry = !data.countryId && this.state.validate ? 'error' : null;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateName = !data.name && this.state.validate ? 'error' : null;
        const validateEssentialFactor = !data.essentialFactor && this.state.validate ? 'error' : null;
        const validateRemark = data.remark && data.remark.length > 100 && this.state.validate ? 'error' : null;
        const validateCommodityDescription = data.commodityDescription && data.commodityDescription.length > 100 && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions) || !hasPermissions(PERMISSION.update, this.props.permissions);
        const {attachments = EMPTY_ARRAY} = details.find(item => item.partId === this.state.currentDetailId) || EMPTY_OBJECT;
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.brandCode',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.specialName',
                defaultMessage: '备件专用名称'
            }),
            dataIndex: 'specialName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.location',
                defaultMessage: '使用位置'
            }),
            dataIndex: 'location',
            render: (text, record) => <TextInput
                id={record.partId}
                name="location"
                value={record.location}
                onBlur={this.onChangeDetail} />
        }, {
            title: formatMessage({
                id: 'newPanel.column.principle',
                defaultMessage: '作用原理'
            }),
            dataIndex: 'principle',
            render: (text, record) => <TextInput
                id={record.partId}
                name="principle"
                value={record.principle}
                onBlur={this.onChangeDetail} />
        }, {
            title: formatMessage({
                id: 'newPanel.column.division',
                defaultMessage: '分工'
            }),
            dataIndex: 'division',
            render: (text, record) => <TextInput
                id={record.partId}
                name="division"
                value={record.division}
                onBlur={this.onChangeDetail} />
        }, {
            title: formatMessage({
                id: 'newPanel.column.consume',
                defaultMessage: '2年国际消耗'
            }),
            dataIndex: 'consume',
            render: (text, record) => (
                <LocalizeInputNumber
                    min={0}
                    id={record.partId}
                    precision={2}
                    value={text} onBlur={this.onUpdateQuantity}/>
            )
        }, {
            title: formatMessage({
                id: 'newPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCategory',
                defaultMessage: '备件分类'
            }),
            dataIndex: 'partCategory',
        }, {
            title: formatMessage({
                id: 'newPanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            dataIndex: 'minPackSize',
        }, {
            title: formatMessage({
                id: 'newPanel.column.overseaOnly',
                defaultMessage: '是否海外专用'
            }),
            dataIndex: 'overseaOnly',
        }, {
            title: formatMessage({
                id: 'newPanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'partId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => {
                const menus = [
                    {
                        id: 'delete',
                        children: (
                            <a key="delete" data-id={text} onClick={this.onDeleteDetail}>
                                {this.props.intl.formatMessage({
                                    id: 'add.delete',
                                    defaultMessage: '删除'
                                })}
                            </a>
                        ),
                    }, {
                        id: 'upload',
                        children: (
                            <a key="upload" onClick={this.onClickUpload} data-id={text}>
                                {this.props.intl.formatMessage({
                                    id: 'add.upload',
                                    defaultMessage: '附件管理'
                                })}
                            </a>
                        ),
                    }
                ];
                return <DropdownMenu key={record.partId} menus={menus} primaryLength={1} id={record.partId} />;
            }
        }];
        return (
            <div className="form-standard">
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'newPanel.file.modal.title',
                        defaultMessage: '附件管理'
                    })}
                    width="60%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showFile}
                    onCancel={this.onCloseFileModal}>
                    <Row>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FileUpload onChange={this.onChangeUpload} onRemove={this.onRemove} fileList={attachments} />
                        </Col>
                    </Row>
                </Modal>
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '订单基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.operation.countryId',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateCountry}
                                        required>
                                        <WrappedSelect
                                            name="countryId"
                                            options={areas}
                                            value={data.countryId}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '商品编码'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateCode}
                                    required>
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.name',
                                        defaultMessage: '商品名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateName}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.englishName',
                                        defaultMessage: '英文名称'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="englishName"
                                            value={data.englishName}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.essentialFactor',
                                        defaultMessage: '申报要素'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateEssentialFactor}
                                    required>
                                        <TextInput
                                            name="essentialFactor"
                                            value={data.essentialFactor}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.firstUnit',
                                        defaultMessage: '法定第一单位'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="firstUnit"
                                            value={data.firstUnit}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.secendUnit',
                                        defaultMessage: '法定第二单位'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="secendUnit"
                                            value={data.secendUnit}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.conditions',
                                        defaultMessage: '海关监管条件'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="conditions"
                                            value={data.conditions}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.quarantineCategory',
                                        defaultMessage: '检验检疫类别'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="quarantineCategory"
                                            value={data.quarantineCategory}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.commodityDescription',
                                        defaultMessage: '商品描述'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateCommodityDescription}>
                                        <TextInput
                                            type="textarea"
                                            name="commodityDescription"
                                            value={data.commodityDescription}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} validateStatus={validateRemark}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '申报要素清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '新增清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartSelectPanel &&
                        <PartSelectPanel
                            selectKey={data.id}
                            onCancel={this.onClosePartSelectPanel}
                            onSelect={this.onSelectPart} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    areas: PropTypes.array,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onNewOrUpdate
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const areas = initData.areas ? initData.areas.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return areas;
    }
);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
    areas: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onNewOrUpdate(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
